#include "TcpServer.hpp"
#include "protocol.hpp"
#include <string>
#include <iostream>
#include <unistd.h>
#include <ctime>
#include <cassert>

void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    MySocket sockfd;
    sockfd.Socket();
    bool ret = sockfd.Connect(serverip, serverport);
    if (!ret)
        return 1;

    srand(time(nullptr) ^ getpid());
    int cnt = 1;
    std::string opers = "+-*/%=&^";

    std::string inbuffer_stream;
    while (cnt <= 10)
    {
        std::cout << "第" << cnt++ << "次测试....\n";
        int x = rand() % 100 + 1;
        usleep(1234);
        int y = rand() % 100;
        usleep(4321);
        char op = opers[rand() % opers.size()];
        Request req(x, y, op);
        req.DebugPrint();

        std::string package;
        req.Serialize(&package);

        package = Encode(package);

        std::cout << "最新发出去的请求: \n" << package;
        write(sockfd.Fd(), package.c_str(), package.size());

        // 设置套接字为非阻塞等待
        // int flags = fcntl(sockfd.Fd(), F_GETFL, 0);
        // fcntl(sockfd.Fd(), F_SETFL, flags | O_NONBLOCK);

        char buffer[128];
        ssize_t n = read(sockfd.Fd(), buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer;
            std::string content;
            bool r = Decode(inbuffer_stream, &content);
            assert(r);
            Response resp;
            r = resp.Deserialize(content);
            assert(r);
            resp.DebugPrint();
            sleep(1);
        }
    }
    sockfd.Close();
    return 0;
}